'use client'

import React, { useState, useEffect, useRef } from 'react'
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

// 定义方向类型
type Direction = 'UP' | 'DOWN' | 'LEFT' | 'RIGHT'

// 定义坐标类型
interface Coordinate {
    x: number
    y: number
}

const CANVAS_SIZE = 300
        const SNAKE_SIZE = 10
        const FOOD_SIZE = 10
        const GAME_SPEED = 100

export default function SnakeGame() {
  const canvasRef = useRef<HTMLCanvasElement | null>(null)
  const [snake, setSnake] = useState<Coordinate[]>([{ x: 150, y: 150 }])
  const [food, setFood] = useState<Coordinate>({ x: 100, y: 100 })
  const [direction, setDirection] = useState<Direction>('RIGHT')
  const [gameOver, setGameOver] = useState<boolean>(false)
  const [score, setScore] = useState<number>(0)

    useEffect(() => {
    const handleKeyPress = (e: KeyboardEvent) => {
        switch (e.key) {
            case 'ArrowUp':
                setDirection('UP')
                break
            case 'ArrowDown':
                setDirection('DOWN')
                break
            case 'ArrowLeft':
                setDirection('LEFT')
                break
            case 'ArrowRight':
                setDirection('RIGHT')
                break
        }
    }

    document.addEventListener('keydown', handleKeyPress)

    return () => {
        document.removeEventListener('keydown', handleKeyPress)
    }
  }, [])

    useEffect(() => {
    if (gameOver) return

    const moveSnake = () => {
        setSnake((prevSnake) => {
        const newSnake = [...prevSnake]
        const head = { ...newSnake[0] }

        switch (direction) {
            case 'UP':
                head.y -= SNAKE_SIZE
                break
            case 'DOWN':
                head.y += SNAKE_SIZE
                break
            case 'LEFT':
                head.x -= SNAKE_SIZE
                break
            case 'RIGHT':
                head.x += SNAKE_SIZE
                break
        }

        // 检查是否吃到食物
        if (head.x === food.x && head.y === food.y) {
            setScore((prevScore) => prevScore + 1)
            setFood(getRandomFood())
        } else {
            newSnake.pop()
        }

        // 检查是否撞到墙或自己
        if (
                head.x < 0 ||
                        head.x >= CANVAS_SIZE ||
                        head.y < 0 ||
                        head.y >= CANVAS_SIZE ||
                        newSnake.some((segment) => segment.x === head.x && segment.y === head.y)
        ) {
            setGameOver(true)
            return prevSnake
        }

        newSnake.unshift(head)
        return newSnake
      })
    }

    const gameLoop = setInterval(moveSnake, GAME_SPEED)

    return () => clearInterval(gameLoop)
  }, [direction, food, gameOver])

    useEffect(() => {
    if (!canvasRef.current) return

    const canvas = canvasRef.current
    const ctx = canvas.getContext('2d')

    if (!ctx) return

            // 清空画布
            ctx.clearRect(0, 0, CANVAS_SIZE, CANVAS_SIZE)

    // 绘制蛇
    ctx.fillStyle = 'green'
    snake.forEach((segment) => {
            ctx.fillRect(segment.x, segment.y, SNAKE_SIZE, SNAKE_SIZE)
    })

    // 绘制食物
    ctx.fillStyle = 'red'
    ctx.fillRect(food.x, food.y, FOOD_SIZE, FOOD_SIZE)
  }, [snake, food])

  const getRandomFood = (): Coordinate => {
        return {
                x: Math.floor(Math.random() * (CANVAS_SIZE / FOOD_SIZE)) * FOOD_SIZE,
                y: Math.floor(Math.random() * (CANVAS_SIZE / FOOD_SIZE)) * FOOD_SIZE,
    }
    }

  const restartGame = () => {
        setSnake([{ x: 150, y: 150 }])
        setFood(getRandomFood())
        setDirection('RIGHT')
        setGameOver(false)
        setScore(0)
    }

    return (
            <Card className="w-full max-w-md mx-auto">
      <CardHeader>
        <CardTitle className="text-2xl font-bold text-center">贪吃蛇游戏</CardTitle>
      </CardHeader>
      <CardContent className="flex flex-col items-center">
        <canvas
            ref={canvasRef}
    width={CANVAS_SIZE}
    height={CANVAS_SIZE}
    className="border border-gray-300"
            />
        <div className="mt-4 text-lg">得分: {score}</div>
            {gameOver && (
                    <div className="mt-4 text-center">
            <div className="text-xl font-bold text-red-500 mb-2">游戏结束!</div>
            <Button onClick={restartGame}>重新开始</Button>
          </div>
        )}
      </CardContent>
    </Card>
  )
}